import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

/**
 * This program is a currency converter.
 * 
 * @author Tamer Saadeh
 * @since 14/02/2010
 * @version 1.4
 * 
 * This update included:
 * 1. Speed fix (except for the first run of the day)
 * 2. Better Algorithm
 * 3. Minor bug fixes
 * 4. Update feature CHF as a new currency conversion
 * 
 * Next update will include:
 * 1. Speed fix (try to make it get the rates faster)
 * 2. Bug fixes (if any found)
 * 3. Add more currencies
 * 
 */
public class Converter {
	private double[] rate = new double[6];
	private String[] curency = new String[6];
	private String[] url = new String[6];
	private File f;

	public Converter(){
		url[0] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/11656/default.stm";
		url[1] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/12/default.stm";
		url[2] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/13/default.stm";
		url[3] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/11633/default.stm";
		url[4] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/14/default.stm";
		url[5] = "http://newsvote.bbc.co.uk/1/shared/fds/hi/business/market_data/currency/11/11676/default.stm";
		curency[0] = "ILS";
		curency[1] = "USD";
		curency[2] = "EURO";
		curency[3] = "CAD";
		curency[4] = "YEN";
		curency[5] = "CHF";
		f = new File("Rates.txt");
		BufferedReader in;
		String line = "";
		Calendar cal = Calendar.getInstance();
		long dayMS = 24*60*60*1000;
		long difference = cal.getTimeInMillis()-f.lastModified();
		long daysOld = difference/dayMS;
		if(!f.exists() || daysOld>=2 || f.length() == 0){
			BufferedWriter output = null;
			try {
				output = new BufferedWriter(new FileWriter(f));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			for(int i = 0; i<rate.length; i++){
				try {
					String text = new Double(setup(url[i], i)).toString();
					output.write(text);
					output.write("\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if(daysOld <= 1){
			try {
				in = new BufferedReader(new FileReader(f));
				int i = 0;
				while ((line = in.readLine()) != null) {
					if(i<rate.length){
						rate[i] = new Double(line).doubleValue();
					}
					i++;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {}
		}
	}

	
	public void update(){
		BufferedWriter output = null;
		try {
			output = new BufferedWriter(new FileWriter(f));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String text = "";
		for(int i = 0; i<rate.length; i++){
			try {
				text = new Double(setup(url[i], i)).toString();
				output.write(text);
				output.write("\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private double setup(String link, int index){
		URL url = null;
		BufferedReader in = null;
		String start = "", line = "", text = "", end = "", str = "error";;
		try {
			url = new URL(link);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		try {
			in = new BufferedReader(new InputStreamReader(url.openStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			while ((line = in.readLine()) != null) {
				text += line + "\n";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		start = "<td class=\"stats\" valign=\"top\" align=\"right\">";
		end = "</td>";
		if(text.toLowerCase().contains(start.toLowerCase())){
			int beginIndex = text.indexOf(start)+45;
			int endIndex;
			text = text.substring(beginIndex);
			if(end == null || end == "" || end.equalsIgnoreCase("") || end.equalsIgnoreCase(null) || end.equalsIgnoreCase(" ")){
				str = text.substring(beginIndex);
			}else{
				endIndex = text.indexOf(end);
				str = text.substring(0, endIndex);
			}
		}
		double d = new Double(str).doubleValue();
		rate[index] = d;
		return d;
	}

	public void getRates(){
		System.out.println("Current Rates (compared to GBP):");
		for(int i = 0; i<rate.length;i++){
			System.out.println(curency[i]+": "+rate[i]);
		}
	}

	public double convert(int amount, String from, String to){
		Double amt = new Double(amount);
		for(int i = 0; i<rate.length; i++){
			if(from.equalsIgnoreCase(curency[i])){
				for(int x = 0; x<rate.length; x++){
					if(to.equalsIgnoreCase(curency[x])){
						amt = (amt/rate[i])*rate[x];
					}
				}
			}
		}
		return amt.doubleValue();
	}

	public double convert(double amount, String from, String to){
		Double amt = new Double(amount);
		for(int i = 0; i<rate.length; i++){
			if(from.equalsIgnoreCase(curency[i])){
				for(int x = 0; x<rate.length; x++){
					if(to.equalsIgnoreCase(curency[x])){
						amt = (amt/rate[i])*rate[x];
					}
				}
			}
		}
		return amt.doubleValue();
	}
}